﻿using System;
using System.Configuration;
using System.Globalization;
using System.IO;

namespace VersionStar.App
{
    public static class Logger
    {
        private static readonly StreamWriter LogFile;
        private static readonly bool LogToFile;

        static Logger()
        {
            LogToFile = !string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["LogToFile"]) && bool.Parse(ConfigurationManager.AppSettings["LogToFile"]);

            if (LogToFile)
            {
                string logFileName = "DBPatch " + DateTime.UtcNow.ToString("yyMMdd-HHmmss") + ".log";
                LogFile = new StreamWriter(logFileName);
            }
        }

        public static void Log(string format, params object[] args)
        {
            string str = format != null ? string.Format(format, args) : "NULL";

            Console.WriteLine(str);
            DoLogToFile("trc", str);
        }

        public static void Err(string format, params object[] args)
        {
            string str = format != null ? string.Format(format, args) : "NULL";

            Console.Error.WriteLine(str);
            DoLogToFile("err", str);
        }

        private static void DoLogToFile(string header, string str)
        {
            if (LogToFile)
            {
                LogFile.WriteLine(header + ":" + DateTime.UtcNow.ToString(CultureInfo.InvariantCulture) + " - " + str);
                LogFile.Flush();
            }
        }
    }
}